import React, { useState } from 'react';
import { LockClosedIcon, AcademicCapIcon, EnvelopeIcon } from '@heroicons/react/24/outline';

const ChangePassword = () => {
  const [formData, setFormData] = useState({
    studentId: '',
    verificationCode: '',
    newPassword: '',
    confirmPassword: ''
  });
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [isCodeSent, setIsCodeSent] = useState(false);
  const [codeCountdown, setCodeCountdown] = useState(0);

  const validateForm = (): boolean => {
    const newErrors = {};

    if (!formData.studentId.trim()) {
      newErrors.studentId = '学号不能为空';
    } else if (!/^\d{10,12}$/.test(formData.studentId)) {
      newErrors.studentId = '请输入10-12位数字的学号';
    }

    if (!formData.verificationCode.trim()) {
      newErrors.verificationCode = '验证码不能为空';
    } else if (!/^\d{6}$/.test(formData.verificationCode)) {
      newErrors.verificationCode = '请输入6位数字验证码';
    }

    if (!formData.newPassword.trim()) {
      newErrors.newPassword = '新密码不能为空';
    } else if (formData.newPassword.length < 6) {
      newErrors.newPassword = '密码长度至少6位';
    }

    if (formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSendCode = () => {
    if (!formData.studentId.trim()) {
      setErrors({ studentId: '请先输入学号' });
      return;
    }

    if (!/^\d{10,12}$/.test(formData.studentId)) {
      setErrors({ studentId: '请输入10-12位数字的学号' });
      return;
    }

    // 模拟发送验证码
    setIsCodeSent(true);
    setCodeCountdown(60);
    
    // 模拟倒计时
    const timer = setInterval(() => {
      setCodeCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    // 模拟验证码（实际项目中应该从后端获取）
    console.log('验证码已发送到学号:', formData.studentId);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    // 模拟密码修改
    setTimeout(() => {
      setIsLoading(false);
      alert('密码修改成功！请使用新密码登录');
      setFormData({
        studentId: '',
        verificationCode: '',
        newPassword: '',
        confirmPassword: ''
      });
      setErrors({});
      setIsCodeSent(false);
      setCodeCountdown(0);
    }, 1000);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md mx-auto">
        <div className="text-center">
          <div className="mx-auto h-20 w-20 bg-primary-100 rounded-full flex items-center justify-center">
            <LockClosedIcon className="h-10 w-10 text-primary-600" />
          </div>
          <h2 className="mt-6 text-3xl font-bold text-gray-900">
            修改密码
          </h2>
          <p className="mt-2 text-sm text-gray-600">
            为了您的账户安全，请通过学号验证码修改密码
          </p>
        </div>

        <div className="mt-8 bg-white py-8 px-6 shadow rounded-lg">
          <form className="space-y-6" onSubmit={handleSubmit}>
            {/* 学号输入 */}
            <div>
              <label htmlFor="studentId" className="block text-sm font-medium text-gray-700">
                学号
              </label>
              <div className="mt-1 relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <AcademicCapIcon className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  id="studentId"
                  name="studentId"
                  type="text"
                  value={formData.studentId}
                  onChange={handleInputChange}
                  placeholder="请输入您的学号"
                  className={`appearance-none block w-full pl-10 pr-3 py-2 border rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm ${
                    errors.studentId ? 'border-red-300' : 'border-gray-300'
                  }`}
                />
              </div>
              {errors.studentId && (
                <p className="mt-1 text-sm text-red-600">{errors.studentId}</p>
              )}
            </div>

            {/* 验证码输入 */}
            <div>
              <label htmlFor="verificationCode" className="block text-sm font-medium text-gray-700">
                验证码
              </label>
              <div className="mt-1 flex space-x-3">
                <div className="flex-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <EnvelopeIcon className="h-5 w-5 text-gray-400" />
                  </div>
                  <input
                    id="verificationCode"
                    name="verificationCode"
                    type="text"
                    value={formData.verificationCode}
                    onChange={handleInputChange}
                    placeholder="请输入6位验证码"
                    className={`appearance-none block w-full pl-10 pr-3 py-2 border rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm ${
                      errors.verificationCode ? 'border-red-300' : 'border-gray-300'
                    }`}
                  />
                </div>
                <button
                  type="button"
                  onClick={handleSendCode}
                  disabled={codeCountdown > 0}
                  style={{
                    padding: '8px 16px',
                    fontSize: '14px',
                    fontWeight: '500',
                    borderRadius: '6px',
                    backgroundColor: codeCountdown > 0 ? '#d1d5db' : '#003891',
                    color: codeCountdown > 0 ? '#6b7280' : '#ffffff',
                    border: 'none',
                    cursor: codeCountdown > 0 ? 'not-allowed' : 'pointer',
                    minWidth: '120px'
                  }}
                >
                  {codeCountdown > 0 ? `${codeCountdown}秒后重发` : '发送验证码'}
                </button>
              </div>
              {errors.verificationCode && (
                <p className="mt-1 text-sm text-red-600">{errors.verificationCode}</p>
              )}
            </div>

            {/* 新密码输入 */}
            <div>
              <label htmlFor="newPassword" className="block text-sm font-medium text-gray-700">
                新密码
              </label>
              <div className="mt-1 relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <LockClosedIcon className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  id="newPassword"
                  name="newPassword"
                  type="password"
                  value={formData.newPassword}
                  onChange={handleInputChange}
                  placeholder="请输入新密码 (至少6位)"
                  className={`appearance-none block w-full pl-10 pr-3 py-2 border rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm ${
                    errors.newPassword ? 'border-red-300' : 'border-gray-300'
                  }`}
                />
              </div>
              {errors.newPassword && (
                <p className="mt-1 text-sm text-red-600">{errors.newPassword}</p>
              )}
            </div>

            {/* 确认新密码输入 */}
            <div>
              <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
                确认新密码
              </label>
              <div className="mt-1 relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <LockClosedIcon className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  value={formData.confirmPassword}
                  onChange={handleInputChange}
                  placeholder="请再次输入新密码"
                  className={`appearance-none block w-full pl-10 pr-3 py-2 border rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm ${
                    errors.confirmPassword ? 'border-red-300' : 'border-gray-300'
                  }`}
                />
              </div>
              {errors.confirmPassword && (
                <p className="mt-1 text-sm text-red-600">{errors.confirmPassword}</p>
              )}
            </div>

            {/* 密码安全建议 */}
            <div className="bg-blue-50 border border-blue-200 rounded-md p-4">
              <h4 className="text-sm font-medium text-blue-800 mb-2">密码安全建议:</h4>
              <ul className="text-sm text-blue-700 space-y-1">
                <li>• 长度至少6位，建议8位以上</li>
                <li>• 包含大小写字母、数字和特殊字符</li>
                <li>• 不要使用生日、姓名等个人信息</li>
                <li>• 定期更换密码，不要重复使用</li>
              </ul>
            </div>

            {/* 提交按钮 */}
            <div>
              <button
                type="submit"
                disabled={isLoading}
                className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading ? '修改中...' : '修改密码'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ChangePassword;